# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :users.py
# @Time      :2022/7/21 15:37
# @Author    :吕华龙
import re

from flask import Blueprint, g, request
from flask_restful import Api, Resource, reqparse
from flask import jsonify

from models.model import *
from utils.jwt_tool import JWT_tool

user_bp = Blueprint("user_bp", __name__, url_prefix="/user")

api = Api(user_bp)


# 修改信息视图
class UserView(Resource):
    # 修改个人信息
    def get(self):
        return jsonify({'code': 200, 'msg': '测试'})


@user_bp.before_request
def stu_login():
    req = reqparse.RequestParser()
    req.add_argument("token", location='headers', help="token的错误")
    # print("-------------------------+++++++++++++++",request.path)
    args = req.parse_args()
    j = JWT_tool()
    payload = j.ver_token(args['token'])

    print("======================", payload)
    # if not (payload or request.path in ['/user/login']):
    #     return jsonify({
    #         "code": 400,
    #         "msg": "用户未登录"
    #     })
    # else:
    if not payload:
        payload = None
    g.stu = payload


def required_login(func):
    def warpper(*args, **kwargs):
        if not g.stu:
            return jsonify({'code': 403, 'msg': '用户为登录'})

        return func(*args, **kwargs)

    return warpper


import random
import redis


# 发送验证码
class SmsCodeView(Resource):
    def get(self):
        resp = reqparse.RequestParser()
        resp.add_argument("phone", required=True, help="手机号输入错误")
        args = resp.parse_args()

        # 随机生成验证码
        code = random.randint(10000, 99999)

        # 连接redis
        redis_cli = redis.Redis(host="127.0.0.1", port=6379, password='123', db=4)

        # 将生成的验证码存入redis
        if redis_cli.set(args['phone'], code, ex=3600):
            return jsonify({'code': 200, 'msg': '发送成功', 'sms': code})
        # 否则生成存入redis失败
        else:
            return jsonify({'code': 400, 'msg': '发送失败'})


# 注册登录
class StudentView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        # req.add_argument("name")
        req.add_argument("phone")
        req.add_argument("password")
        req.add_argument("sms_code", type=int)
        args = req.parse_args()
        print("------------->>>>>>>>>>>", args['phone'], type(args['phone']))
        print("------------->>>>>>>>>>>", args['password'], type(args['password']))

        # 根据手机号查询出
        stu_info = Stu.query.filter(Stu.phone == args['phone']).first()
        # print("========================", stu_info.password)
        # 并且判断密码是否相等，如果相等登陆成功返回token
        if stu_info:
            if args['password'] == stu_info.password:
                j = JWT_tool()
                token = j.create_token({
                    "id": stu_info.id,
                    "name": stu_info.name
                }, 3600)
                return jsonify({
                    "code": 200,
                    "msg": "登录成功",
                    "token": token
                })
            # 否则就是密码不对
            else:
                return jsonify({'code': 400, 'msg': '手机号或密码错误！'})
        # 否则就是没有此用户就注册
        else:
            # 连接redis
            redis_cli = redis.Redis(host="127.0.0.1", port=6379, password="123", db=4)
            # 取出此手机号的验证码
            sms_code = redis_cli.get(args['phone'])
            # 判断取出来的验证码和用户输入的验证码是否一样
            print("?>>>>>>>??>>>", sms_code, type(sms_code.decode()), type(sms_code))
            print("??>>>?>?>?>?>?>?>", args['sms_code'], type(args['sms_code']))

            if sms_code.decode() == str(args['sms_code']):
                print("pppppppppppppppppppppppp")
                # 验证码正确就注册到表中
                try:
                    stu_add = Stu(phone=args['phone'], password=args['password'])
                    db.session.add(stu_add)
                    db.session.commit()
                    print("mmmmmmmmmmmmmmmmmmmmmmmmm")
                    print("stu_add.id==============", stu_add.phone)
                    j = JWT_tool()
                    token = j.create_token({
                        "id": stu_add.id,
                        "phone": stu_add.phone
                    }, 3600)
                    return jsonify({'code': 200, 'msg': "注册成功", 'token': token})
                except Exception as e:
                    print("eeeeeeeeeeeeeeee", e)
                    return False

            # 否则就是验证码错误
            else:
                return jsonify({'code': 400, 'smg': '验证码错误'})


# 学生关注老师
class Acce_view(Resource):
    def post(self):
        id = g.stu['id']
        print("g对象里的用户信息---------", id)
        req = reqparse.RequestParser()
        req.add_argument("id")
        args = req.parse_args()
        stu = Stu.query.filter(Stu.id == id).first()
        tec = Teacher.query.filter(Teacher.id == args['id']).first()
        if tec in stu.teachers:
            return jsonify({
                "code": 400,
                "mgs": "用户已经关注"
            })
        stu.teachers.append(tec)
        db.session.commit()
        return jsonify({
            "code": 200,
            "msg": "关注成功"
        })


# 指定学生视图
class StudentTeacherView(Resource):
    # 获取单个学生及学生下的老师
    def get(self):
        resp = reqparse.RequestParser()
        resp.add_argument("id")
        args = resp.parse_args()

        # 查询单个学生
        student = Stu.query.filter(Stu.id == args['id']).first()
        # 查询到学生的老师
        teacher = student.teachers
        print(">>>>>>", teacher)
        print(dir(student))

        # 循环老师拿出数据
        lst_1 = []
        for i in teacher:
            lst_1.append({
                "id": i.id,
                "name": i.name,
                "attention_num": i.attention_num,
                "phone": i.phone,
                "info": i.info,
                "create_time": i.create_time
            })
        # return '1111'
        print("----", lst_1)

        # 自定义数据返回格式
        data = {
            "id": student.id,
            "name": student.name,
            "phone": student.phone,
            "info": student.info,
            "create_time": student.create_time,
            "status": student.status,
            "teacher": lst_1
        }

        # 返回响应
        return jsonify({'code': 200, 'msg': '获取成功', "data": data})


# 全部学生视图
class StudentTeacherAllView(Resource):
    # 获取单个学生及学生下的老师
    def get(self):
        # 查询学生
        student = Stu.query.all()
        print("-----//////", student)
        # 查询到学生的老师
        lst_2 = []
        for i in student:
            teacher_1 = i.teachers
            print("<<<<<<<<<<<<", teacher_1)
            for teacher in teacher_1:
                lst_1 = {
                    "id": teacher.id,
                    "name": teacher.name,
                    "attention_num": teacher.attention_num,
                    "phone": teacher.phone,
                    "info": teacher.info,
                    "create_time": teacher.create_time
                }
                students = {
                    "id": i.id,
                    "name": i.name,
                    "phone": i.phone,
                    "info": i.info,
                    "create_time": i.create_time,
                    "status": i.status,
                    "teacher": lst_1
                }
                lst_2.append(students)
            rds = redis.Redis()
            rds.publish("teachers", i.name)
        # 返回响应
        return jsonify({'code': 200, 'msg': '获取成功', "data": lst_2})


# 创建路由
# 发送验证码
api.add_resource(SmsCodeView, "/sms_code")
api.add_resource(UserView, "/user_info")
api.add_resource(StudentView, "/login")
api.add_resource(Acce_view, '/acce')
# 获取单个学生及老师的信息
api.add_resource(StudentTeacherView, '/stu_tea')
# 全部学生及老师的信息
api.add_resource(StudentTeacherAllView, '/stu_tea_all')
